class PasswordRestsController < ApplicationController
  before_action :valid_user, only: [:edit,:update]
  before_action :check_expiration, only: [:edit, :update]
  before_action :get_user,  only: [:edit, :update]

  def new
  end

  def edit
  end

  def create
    email= params[:password_rest][:email]
    user=User.find_by(email: email)
    if user
      user.create_reset_digest
      UserMailer.activate_email(user).deliver
      # UserMailer.reset_email(@user).deliver
      flash[:info] = "Email sent with password reset instructions"
      redirect_to root_url
    else
      flash.now[:warning]='邮件未发送成功'
      render 'new'
    end
  end

  def update

    if params[:edit_reset][:password].blank? &&
      params[:edit_reset][:password_confirmation].blank?
      render 'edit'
    elsif @user.update_attributes(user_params)
      log_in @user
      redirect_to @user
    elsif
      render 'edit'
    end

  end

  def user_params
    params.require(:edit_reseter).permit(:password, :password_confirmation)
  end
  def get_user
    #获取get页面的用户邮箱找到用户
    @user=User.find_by(email: params[:email])
  end
  def valid_user
    #验证 通过得到邮箱地址中后缀的 base64s生成的token和忘记密码页面存储在数据库的摘要对比进行确认
    #
    unless (@user && @user.activated?&&@user.authenticated?(:reset, params[:id]))
      redirect_to root_url
    end
  end
end
